package com.wnxy.admin.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageInfo;
import com.wnxy.admin.common.ResponseResult;
import com.wnxy.admin.entity.ChargingCard;
import com.wnxy.admin.service.IChargingCardService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.wnxy.admin.entity.Recharge;
import com.wnxy.admin.service.IRechargeService;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

/**
 * <p>
 * 充值信息表 前端控制器
 * </p>
 *
 * @author All
 * @since 2023-11-29
 */
@RestController
@RequestMapping("/recharge")
public class RechargeController {

    private final IRechargeService rechargeServiceImpl;
    private final IChargingCardService chargingCardServiceImpl;
    public RechargeController(IRechargeService rechargeServiceImpl, IChargingCardService chargingCardServiceImpl){
        this.rechargeServiceImpl = rechargeServiceImpl;
        this.chargingCardServiceImpl = chargingCardServiceImpl;
    }

    @CrossOrigin
    @GetMapping("/page/{pageNum}/{pageSize}")
    public ResponseResult page(@PathVariable Integer pageNum,
                               @PathVariable Integer pageSize,
                               @RequestParam(required = false) String keyword) {
        PageInfo<Recharge> page = rechargeServiceImpl.getAll(pageNum, pageSize, keyword);
        return ResponseResult.ok(page);
    }

    @Transactional
    @PostMapping("save")
    public ResponseResult save(@RequestBody Recharge recharge) {
        rechargeServiceImpl.save(recharge);
        if (recharge.getRechargeStatus() == 1) {
            ChargingCard chargingCard = chargingCardServiceImpl.getOne(Wrappers.lambdaQuery(ChargingCard.class)
                    .eq(ChargingCard::getChargingCardNumber, recharge.getChargingCardNumber()));

            BigDecimal rechargeAmount = recharge.getAmount();
            BigDecimal newBalance = chargingCard.getChargingCardMoney().add(rechargeAmount);

            // 更新充电卡余额
            if (newBalance.compareTo(chargingCard.getChargingCardMoney()) >= 0) {

                chargingCard.setChargingCardMoney(newBalance);
                chargingCardServiceImpl.updateById(chargingCard);
                rechargeServiceImpl.save(recharge);
            }
        }
        return ResponseResult.ok();
    }
}
